package net.huashitong.util;

import com.google.common.base.Strings;
import com.sirdc.modules.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public  class UtilsTools {
    public static  final  String CODE ="200";
    public static  final String ERROR="500";

    public static String SysUserId;
    public static String SysUserName;
//    public final static String msgapiKey= "b3232c91e3336d52ae80b73bb0a1cb91";
    public final static String msgapiKey= "";

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    /**
     * 获取IP
     * @param request
     * @return
     */
    public static String getClientAddress(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (("0:0:0:0:0:0:0:1").equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
      /*  if (!isIpAddress(ip)) {
            return "";
        }*/
        return ip;
    }
    /**
     * 替换字符串
     * @param s
     * @return
     */
    public static String replaceString(String s) {
        return s.replace("【", "[").replace("】", "]").replace("&ldquo;", "\"").replace("&rdquo;", "\"");
    }

    public static String replaceSave(String s){
        return s.replace("【", "[").replace("】", "]").replace("&ldquo;", "\"").replace("&rdquo;", "\"");
    }
    //获取当当前年月日
    public static String getCurrentDate() {

        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sf.format(date);

        return currentDate;
    }

    //获取当前时间
    public static String getCurrentTime() {
		/*Calendar cal = Calendar.getInstance();
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		int minute = cal.get(Calendar.MINUTE);
		int second = cal.get(Calendar.SECOND);*/
        Date date  = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
        String time  = sf.format(date);
        return time;
    }

    //获取年份
    public static String getCurrenYear ()
    {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy");
        String currentYear = sf.format(date);
        return currentYear;
    }

    //获取当前月份
    public static String getCurrentMonth()
    {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMM");
        String currentMonth = sf.format(date);
        return currentMonth;
    }

    //获取当前日期时间
    public static String getCurrentDateTime(){
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        String currnetDateTime = sf.format(date);
        return currnetDateTime;
    }

    /**
     * 字符串转日期 YYYYMMDD 格式
     * @param StringDate
     * @return date
     */
    public static Date StringToDate (String StringDate) throws ParseException {
        // = new Date();
        Date date =sdf.parse(StringDate);
        return date;
    }

    /**
     * 日期转字符串 YYYMMDD
     * @param date
     * @return
     */
    public static String DateToString(Date date)
    {

        String Stringdate =sdf.format(date);
        return Stringdate;
    }

    /**
     * 日期加天数的日期
     * @param num
     * @param StringDate
     * @return
     * @throws ParseException
     */
    public static String plusDay(int num ,String StringDate) throws ParseException {
        Date date  = sdf.parse(StringDate);
        System.out.println("现在日期为：" + date);
        Calendar cal  = Calendar.getInstance();
        cal.add(Calendar.DATE,num);
        date=cal.getTime();
        String currentDate = sdf.format(date);
        System.out.println("改变后的日期为：" + currentDate);
        return currentDate;
    }

    //属性复制器 add by xxq
    public static void copyPro(Object obj,Object obj2){
        try {
            BeanInfo soursebean = Introspector.getBeanInfo(obj.getClass(), Object.class);
            PropertyDescriptor[] sourpro =soursebean.getPropertyDescriptors();
            BeanInfo soursebean2 = Introspector.getBeanInfo(obj2.getClass(), Object.class);
            PropertyDescriptor[] sourpro2 =soursebean2.getPropertyDescriptors();

            for (int i = 0; i < sourpro.length; i++) {
                for (int j = 0; j < sourpro2.length; j++) {
                    if(sourpro[i].getName().equals(sourpro2[j].getName())&&sourpro[i].getPropertyType().equals(sourpro2[j].getPropertyType())  ){
                        sourpro2[j].getWriteMethod().invoke(obj2, sourpro[i].getReadMethod().invoke(obj));
                        break;
                    }
                }
            }
        } catch (IntrospectionException e) {
            // TODO Auto-generated catch block

        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 求当前日期
     * @return
     */
    public static String getNowDate(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        return df.format(new Date());
    }
    public static String getDate(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");//设置日期格式
        return df.format(new Date());
    }
    public static String getDateByMD(){
        SimpleDateFormat df = new SimpleDateFormat("MM月dd日");//设置日期格式
        return df.format(new Date());
    }
    public static String getDateByYMD(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");//设置日期格式
        return df.format(new Date());
    }


    private static Calendar getCalendar(String dateStr,String parseFormat) throws ParseException{
        SimpleDateFormat df = new SimpleDateFormat(StringUtils.isBlank(parseFormat)?"yyyy-MM-dd":parseFormat);
        Date date = StringUtils.isNotBlank(dateStr)?df.parse(dateStr): new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        return calendar;
    }


    /**
     *
     * @param dateStr
     * @param parseFormat 日期格式化
     * @return
     * @throws Exception
     */
    public static String getThisWeekFive(String dateStr,String parseFormat) throws ParseException{
        Calendar calendar = getCalendar(dateStr,parseFormat);
        SimpleDateFormat df = new SimpleDateFormat(StringUtils.isBlank(parseFormat)?"yyyy-MM-dd":parseFormat);
        // 1 周日      7 周六
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        //System.out.println("月第几天：" + dayOfMonth);
        //System.out.println("周几 从周日1：" + dayOfWeek);
        //calendar.add(3, 1);
        //System.out.println("下周 同星期几：" + df.format(calendar.getTime()));
        if (dayOfWeek == 6) {
            //周五
        } else if (dayOfWeek == 1) {
            calendar.add(Calendar.DATE, -2);
        } else if (dayOfWeek == 7) {
            //周六
            calendar.add(Calendar.DATE, -1);
        } else {
            // 2   +4
            //3   +3
            //4   +2
            //5   +1
            calendar.add(Calendar.DATE, 6 - dayOfWeek);
        }
        return df.format(calendar.getTime());
    }

    /**
     *   给定日期的 本周
     * @param dateStr
     * @param parseFormat  日期格式化
     * @param num  1 这周一   ->   7 这周日
     * @return
     * @throws Exception
     */
    public static String getThisWeekNum(String dateStr,String parseFormat,int num) throws ParseException{
        Calendar calendar = getCalendar(dateStr,parseFormat);
        SimpleDateFormat df = new SimpleDateFormat(StringUtils.isBlank(parseFormat)?"yyyy-MM-dd":parseFormat);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (num==7) {
            if (dayOfWeek !=1) {
                calendar.add(Calendar.DATE, 8-dayOfWeek);
            }
        } else {
            calendar.add(Calendar.DATE, num+1 -dayOfWeek);
        }
        return df.format(calendar.getTime());
    }

    public static String getNextWeekSame(String dateStr,String parseFormat) throws ParseException{
        Calendar calendar = getCalendar(dateStr,parseFormat);
        SimpleDateFormat df = new SimpleDateFormat(StringUtils.isBlank(parseFormat)?"yyyy-MM-dd":parseFormat);
        //calendar.add(Calendar.DATE, 7);
        calendar.add(3, 1);
        return df.format(calendar.getTime());
    }
    /**
     * 给定日期的 下周
     * @param dateStr
     * @param parseFormat  日期格式化
     * @param num  1 这周一   ->   7 这周日
     * @return
     * @throws Exception
     */
    public static String getNextWeekNum(String dateStr,String parseFormat,int num) throws ParseException {
        Calendar calendar = getCalendar(dateStr,parseFormat);
        SimpleDateFormat df = new SimpleDateFormat(StringUtils.isBlank(parseFormat)?"yyyy-MM-dd":parseFormat);
        String thisWeek = getThisWeekNum(dateStr,parseFormat,num);
        return getNextWeekSame(thisWeek,parseFormat);
    }

    /**
     *
     * @param dateStr 从数据库查找的、周期任务获取月份
     * @param parseFormat
     * @param zero 是否补0
     * @return
     * @throws Exception
     */
    public static String getMonth(String dateStr,String parseFormat,boolean zero) throws ParseException {
        Calendar calendar = getCalendar(dateStr,parseFormat);
        SimpleDateFormat df = new SimpleDateFormat(StringUtils.isBlank(parseFormat)?"yyyy-MM-dd":parseFormat);
        int month = calendar.get(Calendar.MONTH) +1;
        if (zero){
            if (month<10){
                return  "0"+month +"";
            }
        }
        return  month +"";
    }


    public static void main(String[] args) {
        try {
            System.out.println("这周五："+UtilsTools.getThisWeekFive(null,null));
            System.out.println("下周五："+UtilsTools.getThisWeekFive("2019/09/23","yyyy/MM/dd"));
            System.out.println("这周三："+UtilsTools.getThisWeekNum(null,null,3));
            System.out.println("9-23的周三："+UtilsTools.getThisWeekNum("2019-09-23",null,3));
            System.out.println("9-23的周五："+UtilsTools.getThisWeekNum("2019-09-23",null,5));
            System.out.println("下周三："+UtilsTools.getNextWeekNum(null,null,3));
            System.out.println("下周日："+UtilsTools.getNextWeekNum(null,null,7));
            System.out.println("本月："+UtilsTools.getMonth(null,null,true));
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}
